
import { RouteRecordRaw } from 'vue-router'
import { defineStore } from 'pinia'
import useUserStore from './user'
import router from '@/router'

import { findRootPathRoute, generatorRoutes, mapTwoLevelRouter } from '../help'
import { constantRoutes } from '@/router/routes/constants'


const usePermissionStore = defineStore('permission-route', {
  state: () => {
    return {
      perList:[] as any[],
      permissionRoutes: [] as RouteRecordRaw[],
    }
  },
  getters: {
    getPermissionSideBar(state) {
      return state.permissionRoutes.filter((it) => {
        return it.meta && !it.meta.hidden
      })
    },
    getPermissionSplitTabs(state) {
      return state.permissionRoutes.filter((it) => {
        return it.meta && !it.meta.hidden && it.children && it.children.length > 0
      })
    },
  },
  actions: {
    hasPermisson(permissionValue:string){

       let l = JSON.parse(sessionStorage.getItem('perList')|| '[]')
       return l.includes(permissionValue)
    },
    async getRoutes(data: { userId: number; roleId: number }) {
      try {

        let list = sessionStorage.getItem('menuList')
        if (list !== null) {

          return generatorRoutes(JSON.parse(list))

        } else {
          throw new Error()
        }
      } catch (error) {

        return generatorRoutes([
          // {
          //   parentPath: '',
          //   menuUrl: '/welcome',
          //   menuName: '主控台',
          //   "icon": "icon-settings",
          //   "routeName": 'welcome',
          //   children: [
          //     {
          //       localFilePath: '/index/welcome.vue',
          //       parentPath: '',
          //       menuUrl: '/welcome',
          //       menuName: '首页',
          //       "icon": "icon-settings",
          //       "routeName": 'welcome',
          //     }
          //   ]
          // }

        ])

      }
    },
    async initPermissionRoute() {
      const userStore = useUserStore()
      // 加载路由
      const accessRoutes = await this.getRoutes({
        roleId: userStore.roleId,
        userId: userStore.userId,
      })


      const mapRoutes = mapTwoLevelRouter(accessRoutes)
      mapRoutes.forEach((it: any) => {
        router.addRoute(it)
      })
      // 配置 `/` 路由的默认跳转地址
      router.addRoute({
        path: '/',
        redirect: findRootPathRoute(accessRoutes),
        meta: {
          hidden: true,
        },
      })
      // 这个路由一定要放在最后
      router.addRoute({
        path: '/:pathMatch(.*)*',
        redirect: '/',
        meta: {
          hidden: true,
        },
      })
      this.permissionRoutes = [...constantRoutes, ...accessRoutes]
    },
    isEmptyPermissionRoute() {
      return !this.permissionRoutes || this.permissionRoutes.length === 0
    },
    reset() {
      this.$reset()
    },
  },
  presist: {
    enable: true
    
  },
  
})

export default usePermissionStore
